<template>
    <div class="refund">
        <div class="refund-form" v-if="showForm">
            <div class="refund-item">
                <div class="refund-item-pic">
                    <img :src="item.thumb" class="pic" alt="">
                </div>
                <div class="flex-fill">
                    <div class="refund-item-title">{{item.title}}</div>
                    <div class="refund-item-sku">{{item.sku_title}}</div>
                </div>
            </div>
            <van-form label-width="70px">
                <van-field label="服务类型">
                    <template #input>
                        <van-radio-group v-model="refund.refund_type" direction="horizontal">
                            <van-radio :name="1">仅退款</van-radio>
                            <van-radio :name="2">退款退货</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
                <van-field label="货物状态">
                    <template #input>
                        <van-radio-group v-model="refund.receive_state" direction="horizontal">
                            <van-radio :name="1">已收到货</van-radio>
                            <van-radio :name="0">未收到货</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
                <van-field
                        readonly
                        clickable
                        name="picker"
                        :value="refund.refund_reason"
                        label="退货原因"
                        placeholder="点击选择退货原因"
                        @click="showPicker = true"
                />
                <van-field
                        name="picker"
                        label="退款金额"
                        v-model="refund.refund_amount"
                        type="number"
                >
                    <template #right-icon>
                        <div>最多￥{{item.total_fee}},包含运费￥{{item.shipping_fee}}</div>
                    </template>
                </van-field>
                <van-field label="退款说明" type="textarea" v-model="refund.refund_desc"/>
                <van-field label="上传图片">
                    <template #input>
                        <div class="flex-fill">
                            <van-uploader
                                    v-model="imgFiles"
                                    :max-count="3"
                                    :max-size="3 * 1024 * 1024"
                                    :after-read="afterRead"
                                    :multiple="true"
                            />
                            <p class="tips">上传凭证,最多3张</p>
                        </div>
                    </template>
                </van-field>
                <div style="padding: 15px 0">
                    <van-button round type="info" class="w-100" @click="handleSubmit">提交</van-button>
                </div>
            </van-form>
        </div>

        <template v-else>
            <div class="refund-info" v-if="refund.refund_id">
                <h3 v-if="refund.refund_state===1">你已成功发起退款申请，请耐心等待商家确认。</h3>
                <h3 v-if="refund.refund_state===2">商家已拒绝你的退款申请。</h3>
                <h3 v-if="refund.refund_state===3">商家已同意退货，请将货物回寄给商家。</h3>
                <h3 v-if="refund.refund_state===4">货物已寄出，等待商家确认。</h3>
                <h3 v-if="refund.refund_state===5">退款成功，货款已原路退回。</h3>
                <ul class="tips">
                    <li>商家同意或者超时未处理，系统将退款给你</li>
                    <li>如果商家决绝，你可以修改退款申请后再次发起，商家会重新处理</li>
                </ul>
                <div class="op-buttons" v-if="refund.refund_state===(1||2)">
                    <van-button size="small" @click="handleRevoke">撤销申请</van-button>
                    <van-button size="small" type="info" plain @click="handleEdit">修改申请</van-button>
                </div>
                <div class="h30"></div>
                <h3>退款信息</h3>
                <div class="refund-info-detail">
                    <dl>
                        <dt>服务类型:</dt>
                        <dd>{{refund.refund_type_des}}</dd>
                    </dl>
                    <dl>
                        <dt>退款原因:</dt>
                        <dd>{{refund.refund_reason}}</dd>
                    </dl>
                    <dl>
                        <dt>退款金额:</dt>
                        <dd>{{refund.refund_amount}}</dd>
                    </dl>
                    <dl>
                        <dt>申请时间:</dt>
                        <dd>{{refund.created_at}}</dd>
                    </dl>
                    <dl>
                        <dt>退款编号:</dt>
                        <dd>{{refund.refund_no}}</dd>
                    </dl>
                    <dl v-if="refund.refund_desc">
                        <dt>退款说明:</dt>
                        <dd>{{refund.refund_desc}}</dd>
                    </dl>
                </div>
            </div>
        </template>
        <template v-if="refund.refund_state===3">
            <div class="h30"></div>
            <h3>填写退货物流信息</h3>
            <refund-shipping :refund="refund" @save="onSaveShipping"></refund-shipping>
        </template>
        <van-popup v-model="showPicker" position="bottom">
            <van-picker
                    show-toolbar
                    :columns="reasons"
                    @confirm="onChooseReason"
                    @cancel="showPicker = false"
                    title="选择退款原因"
            />
        </van-popup>
    </div>
</template>

<script>
    import RefundShipping from "./RefundShipping";
    import {compressImage} from "../lib/compressimg";

    export default {
        name: "ApplyApp",
        components: {
            RefundShipping
        },
        data: function () {
            return {
                item: _config.item,
                refund: {
                    refund_type: 1,
                    receive_state: 1,
                    refund_amount: _config.item.total_fee,
                    images: []
                },
                reasons: [],
                showForm: false,
                imgFiles: [],
                submited: false,
                showPicker:false
            }
        },
        mounted() {
            this.fetchData();
            this.fetchReasons();
        },
        methods: {
            fetchData(){
                const {trade_id} = _config;
                this.$get('/webapi/refund/query', {trade_id}).then(response => {
                    const {refund} = response.data;
                    if (refund) {
                        this.refund = refund;
                        this.imgFiles = refund.images.map(d => ({
                            ...d,
                            url: d.thumb
                        }));
                        this.showForm = false;
                    }
                }).catch(reason => {
                    this.showForm = true;
                });
            },
            fetchReasons() {
                this.$get('/webapi/refundreason/getall').then(response => {
                    this.reasons = response.data.items.map(d=>d.title);
                });
            },
            handlePickedImage: function (img) {
                this.refund.images.push({
                    thumb: img.thumb,
                    image: img.image
                });
            },
            async handleSubmit() {
                const refund = this.refund;
                const {refund_amount, refund_reason} = refund;
                if (!refund_reason) {
                    this.$showToast('请选择退款原因');
                    return false;
                }

                if (isNaN(refund_amount)) {
                    this.$showToast('退款金额必须是数字');
                    return false;
                }

                if (refund_amount <= 0) {
                    this.$showToast('退款金额必须大于0');
                    return false;
                }

                if (this.submited) {
                    return;
                } else {
                    this.submited = true;
                }

                var images = [];
                for (var i = 0; i < this.imgFiles.length; i++) {
                    var imgFile = this.imgFiles[i];
                    if (imgFile.content) {
                        var formData = new FormData();
                        formData.append('file', imgFile.file, imgFile.file.name);
                        var response = await this.$axios.post('/webapi/material/uploadimg', formData, {
                            headers: {'Content-Type': 'multipart/form-data'}
                        });
                        images.push(response.data.image);
                    } else {
                        images.push(imgFile);
                    }
                }

                const {refund_id} = refund;
                if (refund_id) {
                    this.$post('/webapi/refund/update', {refund_id, refund, images}).then(response => {
                        this.refund = response.data.refund;
                        this.imgFiles = this.refund.images.map(d => ({
                            ...d,
                            url: d.thumb
                        }));
                        this.showForm = false;
                    });
                } else {
                    this.$post('/webapi/refund/create', {trade_id: _config.trade_id, refund, images}).then(response => {
                        this.refund = response.data.refund;
                        this.imgFiles = this.refund.images.map(d => ({
                            ...d,
                            url: d.thumb
                        }));
                        this.showForm = false;
                    });
                }
            },
            handleRevoke() {
                this.$dialog.confirm({
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    message: '确定要撤销此次退款申请吗?'
                }).then(() => {
                    const {refund_id} = this.refund;
                    this.$post('/webapi/refund/revoke', {refund_id}).then(response => {
                        window.history.back();
                    });
                });
            },
            handleEdit() {
                this.showForm = true;
                this.submited = false;
            },
            afterRead(imgFile,detail) {
                //console.log(this.refund.images)
                compressImage(imgFile.content, imgFile.file.name).then(res=>{
                    this.imgFiles[detail.index].content = res.base64;
                    this.imgFiles[detail.index].file = res.file;
                });
            },
            onSaveShipping(refund) {
                this.refund = refund;
            },
            onChooseReason(v){
                this.refund.refund_reason = v;
                this.showPicker = false;
            }
        }
    }
</script>

<style lang="scss" scoped>
    body {
        background-color: #fff;
    }
    .van-cell{
        padding: 12px 0 !important;
    }
</style>
